<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>全选反选</title>
    <style>
      table {
        width: 300px;
        margin: 100px auto;
        text-align: center;
        font-size: 14px;
        border-collapse: collapse;
      }

      thead > tr {
        height: 30px;
        background-color: #008dd0;
        color: #ffffff;
      }

      tbody > tr {
        height: 30px;
        background-color: #eef1ee;
      }

      input {
        cursor: pointer;
      }
    </style>
  </head>
  <body>
    <table border="1">
      <thead>
        <tr>
          <td>
            <input type="checkbox" />
          </td>
          <td>商品</td>
          <td>价格(元)</td>
        </tr>
      </thead>

      <tbody>
        <tr>
          <td>
            <input type="checkbox" />
          </td>
          <td>iPhone14</td>
          <td>5999</td>
        </tr>
        <tr>
          <td>
            <input type="checkbox" />
          </td>
          <td>iMac</td>
          <td>12999</td>
        </tr>
        <tr>
          <td>
            <input type="checkbox" />
          </td>
          <td>iPad</td>
          <td>4799</td>
        </tr>
        <tr>
          <td>
            <input type="checkbox" />
          </td>
          <td>Apple Watch</td>
          <td>3599</td>
        </tr>
      </tbody>
    </table>

    <script>
      var checkAll = document.querySelector('thead').querySelector('input'); // 全选
      var boxList = document.querySelector('tbody').querySelectorAll('input');

      // 全选
      checkAll.onclick = function () {
        for (var i = 0; i < boxList.length; i++) {
          boxList[i].checked = checkAll.checked;
        }
      };

      // 点击复选框
      for (var j = 0; j < boxList.length; j++) {
        boxList[j].onclick = function () {
          var flag = true;

          for (var e = 0; e < boxList.length; e++) {
            // 只要有一个没有选中，剩下的循环无需进行了
            if (!boxList[e].checked) {
              flag = false;
              break;
            }
          }
          checkAll.checked = flag;
        };
      }
    </script>
  </body>
</html>
